package project.dade.cn.bst.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.InjectView;
import cn.beecloud.BCPay;
import cn.beecloud.BCQuery;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCBillOrder;
import cn.beecloud.entity.BCPayResult;
import cn.beecloud.entity.BCQueryBillResult;
import cn.beecloud.entity.BCReqParams;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.utils.BillUtils;

/**
 * Created by vain zhou on 2016/3/15.
 */
public class OrderSucessActivity extends ZJPBaseBarActivity implements View.OnClickListener{
    private String order;
    private float price;
    private String amount;
    @InjectView(R.id.orderNO)
    TextView orderNO;
    @InjectView(R.id.money)
    TextView money;
    @InjectView(R.id.btn_pay_now)
    Button pay;
    private KProgressHUD hud;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_generate_success);
        order=getIntent().getStringExtra("number");
        price=getIntent().getFloatExtra("price",0);
        amount=getIntent().getStringExtra("money");
        orderNO.setText(order);
        money.setText(amount);
        pay.setOnClickListener(this);
        //开启测试模式
        BeeCloud.setSandbox(false);
        BeeCloud.setAppIdAndSecret("0dca9499-57e7-4da4-9b81-7ec5d921b3b9",
                "4d70746e-2f81-44aa-b960-7358ff4c2b88");
    }
    //支付结果返回入口
    BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult)bcResult;
            //此处关闭loading界
           hud.dismiss();
            //根据你自己的需求处理支付结果
            //需要注意的是，此处如果涉及到UI的更新，请在UI主进程或者Handler操作
          OrderSucessActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    String result = bcPayResult.getResult();

                    /*
                      注意！
                      所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
                    */
                    if (result.equals(BCPayResult.RESULT_SUCCESS)) {
//                        Toast.makeText(OrderSucessActivity.this, "用户支付成功", Toast.LENGTH_LONG).show();
                        Intent mIntent = new Intent(OrderSucessActivity.this,
                                MyorderActivity.class);
                        startActivity(mIntent);
                        finish();

                    } else if (result.equals(BCPayResult.RESULT_CANCEL))
                        Toast.makeText(OrderSucessActivity.this, "用户取消支付", Toast.LENGTH_LONG).show();
                    else if (result.equals(BCPayResult.RESULT_FAIL)) {
                        String toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                                " # " + bcPayResult.getErrMsg() +
                                " # " + bcPayResult.getDetailInfo();

                        /**
                         * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                         * 不再提供支付宝支付的测试功能，所以给出提示说明
                         */
                        if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                                bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                            toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                        }

                        /**
                         * 以下是正常流程，请按需处理失败信息
                         */

                        Toast.makeText(OrderSucessActivity.this, toastMsg, Toast.LENGTH_LONG).show();
                        Log.e(TAG, toastMsg);


                    } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                        //可能出现在支付宝8000返回状态
                        Toast.makeText(OrderSucessActivity.this, "订单状态未知", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(OrderSucessActivity.this, "invalid return", Toast.LENGTH_LONG).show();
                    }

                    if (bcPayResult.getId() != null) {
//                        //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
//                        Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());
//
//                        //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                        getBillInfoByID(bcPayResult.getId());
                    }
                }
            });
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_pay_now:
                hud = KProgressHUD.create(OrderSucessActivity.this)
                        .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                        .setLabel("正在加载")
                        .setCancellable(true);
                hud.show();
                Map<String, String> mapOptional = new HashMap<String, String>();
                mapOptional = new HashMap<String, String>();
//                mapOptional.put("money", price);
                BCPay.getInstance(OrderSucessActivity.this).reqAliPaymentAsync(
                        "支付宝",    //订单标题
                        (int)price,   //订单金额(分)
                        order,//订单流水号
                        mapOptional,
                        bcCallback);


                break;

        }


    }
    void getBillInfoByID(String id) {

        BCQuery.getInstance().queryBillByIDAsync(id,
                new BCCallback() {
                    @Override
                    public void done(BCResult result) {
                        BCQueryBillResult billResult = (BCQueryBillResult) result;

                        if (billResult.getResultCode() != 0)
                            return;


//                        Log.d(TAG, "------- bill info ------");
//                        BCBillOrder billOrder = billResult.getBill();
//                        Log.d(TAG, "订单唯一标识符：" + billOrder.getId());
//                        Log.d(TAG, "订单号:" + billOrder.getBillNum());
//                        Log.d(TAG, "订单金额, 单位为分:" + billOrder.getTotalFee());
//                        Log.d(TAG, "渠道类型:" + BCReqParams.BCChannelTypes.getTranslatedChannelName(billOrder.getChannel()));
//                        Log.d(TAG, "子渠道类型:" + BCReqParams.BCChannelTypes.getTranslatedChannelName(billOrder.getSubChannel()));
//                        Log.d(TAG, "订单是否成功:" + billOrder.getPayResult());
//
//                        if (billOrder.getPayResult())
//                            Log.d(TAG, "渠道返回的交易号，未支付成功时，是不含该参数的:" + billOrder.getTradeNum());
//                        else
//                            Log.d(TAG, "订单是否被撤销，该参数仅在线下产品（例如二维码和扫码支付）有效:"
//                                    + billOrder.getRevertResult());
//
//                        Log.d(TAG, "订单创建时间:" + new Date(billOrder.getCreatedTime()));
//                        Log.d(TAG, "扩展参数:" + billOrder.getOptional());
//                        Log.w(TAG, "订单是否已经退款成功(用于后期查询): " + billOrder.getRefundResult());
//                        Log.w(TAG, "渠道返回的详细信息，按需处理: " + billOrder.getMessageDetail());

                    }
                });
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}
